package org.example.elmfront.service.Imp;

// OrderServiceImpl 实现类

import org.example.elmfront.entity.Order;
import org.example.elmfront.entity.OrderItem;
import org.example.elmfront.mapper.OrderMapper;
import org.example.elmfront.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;


@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrderMapper orderMapper;


    @Override
    public Long createOrder(Order order) {
        // 设置创建时间和更新时间
        Instant now = Instant.now();
        order.setCreatedAt(now);
        order.setUpdatedAt(now);

        // 插入订单
        orderMapper.insertOrder(order);

        // 返回插入后的订单 ID
        return order.getId();
    }
    @Override
    public Long createOrderFromItems(List<OrderItem> orderItems) {
        // 创建订单
        Order order = new Order();
        // 可以根据业务需求设置订单的其他属性，如订单日期等
        orderMapper.insertOrder(order);


        for (OrderItem item : orderItems) {
            item.setOrderId(order.getId());
            orderMapper.insertOrderItem(item);
        }


        return order.getId();
    }


    @Override
    public Order getOrderById(Long id) {
        return orderMapper.findOrderById(id);
    }


    @Override
    public void updateOrderStatus(Long id, Integer status) {
        orderMapper.updateOrderStatus(id, status);
    }


    @Override
    public void deleteOrder(Long id) {
        orderMapper.deleteOrderById(id);
    }


    @Override
    public void addOrderItem(OrderItem orderItem) {
        orderMapper.insertOrderItem(orderItem);
    }


    @Override
    public List<OrderItem> getOrderItemsByOrderId(Long orderId) {
        return orderMapper.findOrderItemsByOrderId(orderId);
    }


    @Override
    public int countOrders() {
        return orderMapper.countOrders();
    }


    public void confirmOrder(List<OrderItem> orderItems) {
        // 保存订单及订单项目
        // 这里需要添加具体逻辑，如生成订单，保存订单项目等
        // 可以调用 OrderMapper 的方法
        for (OrderItem item : orderItems) {
            // 假设订单已经存在，这里可以根据实际情况处理订单创建逻辑
            orderMapper.insertOrderItem(item);
        }
    }


    public void cancelOrder(List<OrderItem> orderItems) {
        // 删除订单及订单项目
        // 可以调用 OrderMapper 的方法
        for (OrderItem item : orderItems) {
            // 假设根据订单项目删除订单，这里可以根据实际情况处理订单删除逻辑
            orderMapper.deleteOrderItem(item);
        }
    }
}
